//
//  BSSBaseViewController.m
//  BrightSunnySky
//
//  Created by zhoujunchun on 2019/3/6.
//  Copyright © 2019 PURANG. All rights reserved.
//

#import "BSSBaseViewController.h"
#import "YTKNetworkAgent.h"

#import "BSSFileManager.h"
#import "TMRouter.h"
#import "PFVLoginStatue.h"



#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>


@interface BSSBaseViewController ()

@end

@implementation BSSBaseViewController

#pragma mark - 生命周期
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if (_baseRequest) {
        [[YTKNetworkAgent  sharedAgent] cancelRequest:_baseRequest];
    }

}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.navBar.superview) {
        [self.view bringSubviewToFront:self.navBar];
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}

- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = COLORRGB(229, 247, 245);
    //    [self.view.layer addSublayer:self.gradientLayer];
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    //定义导航栏
    [self setupNavigationBar];
}
- (BOOL)popGestureEnabled{
    return YES;
}
#pragma mark - 导航栏 NavigationBar
- (void)setupNavigationBar {
    //关闭系统导航条的现实
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    [self.view addSubview:self.navBar];
    [self.view bringSubviewToFront:self.navBar];
    
    [self setNavBarTitle:self.title];
    [self setNavBarTitleLabelType:BSSNavBarTitleLabelTypeLeft];
    [self setNavBarType:BSSNavBarTypeLight];
    [self setNavBarLeftButtonType:BSSNavBarLeftButtonTypeBack];
    
}
- (void)setNavBarType:(BSSNavBarType)type{
    self.navBar.navBartype = type;
}

- (void)setNavBarTitle:(NSString *)title{
    self.title = title;
}

- (void)setTitle:(NSString *)title {
    super.title = title;
    self.navBar.title = title;
}
- (void)setNavBarTitleLabelType:(BSSNavBarTitleLabelType)titleLabelType{
    self.navBar.titleLabelType = titleLabelType;
}
- (void)setNavBarHidden:(BOOL)hidden{
    self.navBar.hidden = hidden;
}

// left
- (void)setNavBarLeftButtonType:(BSSNavBarLeftButtonType)leftButtonType{
    self.navBar.leftButtonType = leftButtonType;
}

- (void)setNavBarLeftButtonImage:(UIImage *)image{
    [self.navBar clearLeftButton];
    self.navBar.leftButton.hidden = NO;
    self.navBar.leftButton.userInteractionEnabled = YES;
    [self.navBar.leftButton setImage:image forState:UIControlStateNormal];
    [self.navBar.leftButton setBackgroundImage:[UIImage createImageWithColor:[UIColor clearColor] size:CGSizeMake(50, 44)] forState:UIControlStateNormal];
}

// right
- (void)setNavBarRightButtonType:(BSSNavBarRightButtonType)rightButtonType{
    self.navBar.rightButtonType = rightButtonType;
}

- (void)setNavBarRightButtonTitle:(NSString *)title{
    [self.navBar clearRightButton];
    self.navBar.rightButton.hidden = NO;
    self.navBar.rightButton.userInteractionEnabled = YES;
    
    title = [self p_constructTitle:title];
    [self.navBar.rightButton setTitle:title forState:UIControlStateNormal];
    [self.navBar.rightButton setTitleColor:__kColor(21, 79, 21) forState:UIControlStateNormal];
    self.navBar.rightButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    [self.navBar.rightButton setBackgroundImage:[UIImage createImageWithColor:[UIColor clearColor] size:CGSizeMake(50, 44)] forState:UIControlStateNormal];
}

- (void)setNavBarRightButtonImage:(UIImage *)image{
    [self.navBar clearRightButton];
    self.navBar.rightButton.hidden = NO;
    self.navBar.rightButton.userInteractionEnabled = YES;
    [self.navBar.rightButton setImage:image forState:UIControlStateNormal];
    [self.navBar.rightButton setBackgroundImage:[UIImage createImageWithColor:[UIColor clearColor] size:CGSizeMake(50, 44)] forState:UIControlStateNormal];
}


- (void)setNavBarColour{
    
    CAGradientLayer * navGradientLayer = [CAGradientLayer layer];
    navGradientLayer.colors = @[(__bridge id)COLORRGB(255, 136, 0).CGColor,
                                (__bridge id)COLORRGB(255 ,164 ,0).CGColor];
    navGradientLayer.locations = @[@0.0, @1.0];
    navGradientLayer.startPoint = CGPointMake(0, 0);
    navGradientLayer.endPoint = CGPointMake(1, 0.0);
    navGradientLayer.frame = CGRectMake(0, 0, __kScreenWidth__, __kStatusBarHeight__);
    
    [self.navBar.layer addSublayer:navGradientLayer];
}

#pragma mark  BSSBaseNavigationBarDelegate
- (void)bss_navBarLeftButtonClicked:(UIButton *)sender{
    [MBProgressHUD hideHUD];
    if (self.navBar.leftButtonType == BSSNavBarLeftButtonTypeBack) {
        if (self.navigationController.viewControllers.count > 1) {
            [self.navigationController popViewControllerAnimated:YES];
        }else if(self.presentingViewController){
            [self dismissViewControllerAnimated:YES completion:nil];
        }
    }
}

- (void)bss_navBarRightButtonClicked:(UIButton *)sender{
    
}

#pragma mark - 登录相关操作
/**是否要求登录**/
- (BOOL)isNeedLogin
{
    if (![PFVLoginStatue sharedInstance].isLogin) {
        UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还未登录，点击确定去登陆" preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [self presentLoginVC];
        }]];
        [self presentViewController:alertVC animated:YES completion:nil];
        return NO;
    }
    return YES;
}
- (void)presentLoginVC{
    
    UIViewController *controller = [[TMRouter sharedInstance] getViewController:@"PRRouteSchemeController://name=BSSLoginController&native=true"  withParam:nil];
    BSSBaseNavigationController * nav = [[BSSBaseNavigationController alloc] initWithRootViewController:controller];
    [self presentViewController:nav animated:YES completion:nil];
    
}

/**要求登录并有回调**/
- (void)isNeedLoginSuccess:(void (^)(void))success failure:(void (^)(void))failure
{
    void (^loginBlock)(NSInteger loginFlag) = ^(NSInteger loginFlag){
        if (loginFlag == 1) {//登录成功
            success();
        }else{
            failure();
        }
    };
    NSMutableDictionary *TMRouterDic = [NSMutableDictionary dictionary];
    [TMRouterDic setObject:loginBlock forKey:@"loginBlock"];
    [TMRouterDic setObject:@"NeedReload" forKey:@"isNeedReload"];
    UIViewController *controller = [[TMRouter sharedInstance] getViewController:@"PRRouteSchemeController://name=BSSLoginController&native=true"  withParam:TMRouterDic];
    BSSBaseNavigationController * nav = [[BSSBaseNavigationController alloc] initWithRootViewController:controller];
    [self presentViewController:nav animated:YES completion:nil];
    
}


///是否要求认证
- (BOOL)isNeedCompleteInfoVC
{
    if (![PFVLoginStatue sharedInstance].isLogin) {
        [self presentLoginVC];
        return NO;
    }else{
        if ([[BSSFileManager shareBSSFileManager] needIdCertified]) {
            [self presentCompleteInfoVC];
            return NO;
        }
    }
    return YES;
}
///要求认证并有回调
- (void)isNeedCompleteInfoVCSuccess:(void (^)(void))success failure:(void (^)(void))failure
{
    void (^completeInfoBlock)(NSInteger completeInfoFlag) = ^(NSInteger completeInfoFlag){
        if (completeInfoFlag == 1) {//认证成功
            success();
        }else{
            failure();
        }
    };
    NSMutableDictionary *TMRouterDic = [NSMutableDictionary dictionary];
    [TMRouterDic setObject:completeInfoBlock forKey:@"completeInfoBlock"];
    [TMRouterDic setObject:@"NeedReback" forKey:@"isNeedReback"];
    UIViewController *controller = [[TMRouter sharedInstance] getViewController:@"PRRouteSchemeController://name=BSSPersonAuthenticationTableController&native=true"  withParam:TMRouterDic];
    controller.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:controller animated:YES];
}

- (void)presentCompleteInfoVC{
    
    UIAlertController* alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您尚未实名认证信息，是否完成证" preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UIViewController *controller = [[TMRouter sharedInstance] getViewController:@"PRRouteSchemeController://name=BSSPersonAuthenticationTableController&native=true"  withParam:nil];
        controller.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:controller animated:YES];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
    
}

#pragma mark - 相册权限
- (BOOL)jurisdictionoOFThePhoneCamera
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        if ([kSystemVersion floatValue] > 10.1) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请您先去设置允许APP访问您的相册 设置>隐私>照片" preferredStyle:UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }]];
            [self presentViewController:alert animated:YES completion:nil];
            return NO;
        }else{
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请您先去设置允许APP访问您的相册 设置>隐私>照片" preferredStyle:UIAlertControllerStyleAlert];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"开启" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
            }]];
            
            [alert addAction:[UIAlertAction actionWithTitle:@"下次再说" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }]];
            [self presentViewController:alert animated:YES completion:nil];
            return NO;
            
        }
    }
    return YES;
}

- (BOOL)jurisdictionoOFThePhoneAlbum
{
    ALAuthorizationStatus  author = [ALAssetsLibrary authorizationStatus];
    if (author == ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请您先去设置允许APP访问您的相册 设置>隐私>照片" preferredStyle:UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return NO;
    }
    return YES;
}


#pragma mark - alertView
- (void)alertView:(NSString *)message {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)alertViewTitle:(NSString *)title message:(NSString *)message actionTitle:(NSString *)actionTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}




#pragma mark - touchesBegan

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //点击空白 消除键盘
    [self.view endEditing:YES];
}


#pragma mark - getter && setter
- (BSSBaseNavigationBar *)navBar{
    if (!_navBar) {
        _navBar = [[BSSBaseNavigationBar alloc] initWithFrame:CGRectMake(0, 0, __kScreenWidth__, __kNavigationBarHeight__)];
        _navBar.delegate = self;
    }
    return _navBar;
}
- (CAGradientLayer *)gradientLayer{
    if (!_gradientLayer) {
        _gradientLayer = [CAGradientLayer layer];
        _gradientLayer.colors = @[(__bridge id)COLORRGB(254 ,241 ,197).CGColor,
                                  (__bridge id)COLORRGB(255, 212, 138).CGColor];
        _gradientLayer.locations = @[@0.0, @1.0];
        _gradientLayer.startPoint = CGPointMake(0, 0);
        _gradientLayer.endPoint = CGPointMake(1, 0.0);
        _gradientLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    }
    return _gradientLayer;
}

#pragma mark - private

- (NSString *)p_constructTitle:(NSString *)title {
    title  = [title stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return [NSString stringWithFormat:@"  %@  ", title];
}
- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

